# -*- ecoding: utf-8 -*-
# @ModuleName: protoll
# @Author: Kandy
# @Time: 2024-04-24 18:10

import psutil
import os


# 通过指定端口来获取PID
def find_process_by_port(port) -> int:
    for proc in psutil.process_iter(['pid', 'name']):
        try:
            connections = proc.connections()
            for conn in connections:
                if conn.laddr.port == port:
                    # return True
                    print(f"Found process {proc.pid} with port {port}")
                    return proc.pid
        except psutil.AccessDenied:
            pass

def kill_process(pid):
    try:
        os.kill(pid, 9)  # 发送信号9来杀死进程
        print(f"进程 {pid} 已被成功终止。")
    except OSError as e:
        print(f"无法终止进程 {pid}: {e}")
if __name__ == '__main__':
    # # 关闭端口进程
    ports_to_check = [5000, 5010, 5020, 5030]  # 进程端口
    for port in ports_to_check:
        pid = find_process_by_port(port)
        if(pid != None and pid != 0):
            kill_process(pid)
    exit(0)

